package com.atguigu.admin.service.impl;

import com.atguigu.admin.mapper.SysUserMapper;
import com.atguigu.admin.model.dto.RegisterDto;
import com.atguigu.admin.model.entity.SysUser;
import com.atguigu.admin.model.menu.MinIOEnum;
import com.atguigu.admin.model.vo.AssginRoleVo;
import com.atguigu.admin.model.vo.RouterVo;
import com.atguigu.admin.model.vo.SysUserQueryVo;
import com.atguigu.admin.service.*;
import com.atguigu.system.model.entity.dto.UpPasswordDto;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

import static com.atguigu.security.utils.SecurityUtil.encryptPassword;
import static com.atguigu.security.utils.SecurityUtil.matchesPassword;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-10-28
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleService sysRoleService;


    @Value("${minioTemp.endpoint}")
    private String endpoint;

    @Value("${minioTemp.bucketName}")
    private String bucketName;



    //用户列表
    @Override
    public IPage<SysUser> selectPage(Page<SysUser> pageParam, SysUserQueryVo sysUserQueryVo) {
        return baseMapper.selectPage(pageParam, sysUserQueryVo);
    }

    //更改用户状态
    @Override
    public void updateStatus(Long id, Integer status) {
        //根据用户id查询
        SysUser sysUser = baseMapper.selectById(id);
        //设置修改状态
        sysUser.setStatus(status);
        //调用方法修改
        baseMapper.updateById(sysUser);
    }




    /**
     * 根据用户名称获取用户信息（基本信息 和 菜单权限 和 按钮权限数据）
     */
    @Override
    public Map<String, Object> getUserInfo(String username) {
        //根据username查询用户基本信息
        SysUser sysUser = this.getUserInfoByUserName(username);
        //根据userid查询菜单权限值
        Long userId = sysUser.getId();
        Long deptId = sysUser.getDeptId();
        Long postId = sysUser.getPostId();
        List<RouterVo> routerVolist = sysMenuService.getUserMenuList(userId);
        //根据userid查询按钮权限值
        List<String> permsList = sysMenuService.getUserPermsList(userId);
        // 给句userid查询角色
        List<String> userRoleList = sysRoleService.getUserRoleNamesByUserId(userId);
        Map<String, Object> result = new HashMap<>();
        result.put("name", username);
        result.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        result.put("roles", userRoleList);
        //菜单权限数据
        result.put("routers", routerVolist);
        //按钮权限数据
        result.put("buttons", permsList);
        return result;
    }

    @Override
    public SysUser getUserInfoByUserName(String username) {
        return baseMapper.selectOne(new QueryWrapper<SysUser>().eq("username", username));
    }


    @Override
    public Boolean register(RegisterDto registerDto) {
        SysUser user = new SysUser();
        // 用户名
        user.setUsername(registerDto.getUsername());
        // 密码-加密
        user.setPassword(encryptPassword(registerDto.getPassword()));
        // 头像
        user.setHeadUrl("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        // 状态
        user.setStatus(1);
        int insert = baseMapper.insert(user);
        if (insert ==1){
            AssginRoleVo assginRoleVo=new AssginRoleVo();
            LambdaQueryWrapper<SysUser> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getUsername, registerDto.getUsername());
            SysUser user1 = baseMapper.selectOne(queryWrapper);
            assginRoleVo.setUserId(user1.getId());
            ArrayList<Long> longs = new ArrayList<>();
            longs.add(2L);
            assginRoleVo.setRoleIdList(longs);
            sysRoleService.doAssign(assginRoleVo);
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Map<String, Object> getBaseUserInfo(String username) {
        HashMap<String, Object> hashMap = new HashMap<>();
        SysUser sysUser = this.getUserInfoByUserName(username);
        String headUrl = endpoint + "/" + bucketName+ "/" + MinIOEnum.USER_BUCKET_IMAGES.getName() + sysUser.getHeadUrl();
        sysUser.setHeadUrl(headUrl);
        sysUser.setPassword(null);
        hashMap.put("sysUser", sysUser);
        return hashMap;
    }

    @Override
    public boolean resetPassword(UpPasswordDto upPasswordDto, String userName ) {
        SysUser sysUser = this.getUserInfoByUserName(userName);
        boolean b = matchesPassword(upPasswordDto.getOldPassword(), sysUser.getPassword());
        if (upPasswordDto.getPassword().equals(upPasswordDto.getCheckPass()) &&b ){
            sysUser.setPassword(encryptPassword(upPasswordDto.getPassword()));
            return baseMapper.updateById(sysUser)==1;
        }
        return false;
    }
}
